import { forwardRef, useEffect, useState } from 'react';
import { Field } from '@formily/core';
import { useField } from '@formily/react';
import { ProductBatchSelect } from '@/pages/basic/productBatch/components/ProductBatchSelect';

export const EditableProductBatchSelect = forwardRef((props: any, ref: any) => {
  const [loaded, setLoaded] = useState<boolean>(false);
  const field = useField<Field>();

  const onChange = (value: any, option: any) => {
    field.form.values.details[field.index].productBatch = option;
    props.onChange?.(value, option);
  };

  useEffect(() => {
    setLoaded(true);
  }, []);

  if (loaded && field.pattern === 'editable') {
    return <ProductBatchSelect onChange={onChange} value={props.value} />;
  } else {
    return (
      <>
        {field.form.values.details[field.index]?.productBatch?.vendor?.name} /{' '}
        {field.form.values.details[field.index]?.productBatch?.product?.name} /{' '}
        {field.form.values.details[field.index]?.productBatch?.no}
      </>
    );
  }
});
